package db

import (
	"fmt"

	"gorm.io/driver/postgres"
	"gorm.io/gorm"
)

type DBConfig struct {
	Host    string
	Port    string
	DBName  string
	User    string
	Pass    string
	AppName string
}

type DB struct {
	Conn   *gorm.DB
	Config DBConfig
}

func NewPostgresConnect(config DBConfig) (DB, error) {
	dsn := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s application_name=%s",
		config.Host,
		config.Port,
		config.User,
		config.Pass,
		config.DBName,
		config.AppName)

	conn, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
	if err != nil {
		return DB{}, err
	}
	return DB{
		Conn: conn,
	}, nil
}

func (db DB) RowByField(column string, value string, table string) (map[string]interface{}, error) {
	out := map[string]interface{}{}
	db.Conn.Table(table).Take(out, column, value)
	return out, nil
}
